package com.tanhua.manager.util;

import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;

public class AipFaceHelper {

    //设置APPID/AK/SK
    private static final String APP_ID = "25219655";
    private static final String API_KEY = "xoKusy3UBkWapUSwD4eqbm3I";
    private static final String SECRET_KEY = "woUxt3cvzI1AXrjKSugbmW412KUotpXX";

    private static AipFace client = null;

    static {
        if (client == null) {
            client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
        }
    }

    /**
     * 从百度云AI中根据图片查找用户绑定的id
     */
    public static String faceSearch(String image) {
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "LOW");// 图片质量控制
        options.put("liveness_control", "LOW");//活体检测控制
        options.put("max_user_num", "1"); // 查找后返回的用户数量,返回相似度最高的几个用户

        //调用api完成根据图片识别
        JSONObject res = client.search(image, "BASE64", "tanhua",options);
        System.out.println(res.toString());
        //解析返回值res
		/*if(res.has("error_code") && res.getInt("error_code")==0) {
			JSONObject result = res.getJSONObject("result");
			JSONArray userList = result.getJSONArray("user_list");
			if(userList.length()>0) {
				JSONObject user = userList.getJSONObject(0);
				return user.getString("user_id");
			}
		}*/

        if(res.has("error_code") && res.getInt("error_code")==0) {
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
            System.out.println("userList"+userList);
            if(userList.length()>0) {
                JSONObject user = userList.getJSONObject(0);
                Double score = (Double) user.get("score");
                if (score > 80) {
                    return user.getString("user_id");
                }
            }
        }
        return null;
    }
}
